package com.atguigu.guli.service.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.oss.config.OssProperties;
import com.atguigu.guli.service.oss.service.FileService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private OssProperties ossProperties;

    private String scheme;
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    @PostConstruct  // 自动以初始化方法, 让它在构造器调用之后执行
    public void init() {
        this.scheme = ossProperties.getScheme();
        this.endpoint = ossProperties.getEndpoint();
        this.accessKeyId = ossProperties.getAccessKeyId();
        this.accessKeySecret = ossProperties.getAccessKeySecret();
        this.bucketName = ossProperties.getBucketName();
    }

    @Override
    public String uploadFile(MultipartFile file, String module) {

        String originalFilename = file.getOriginalFilename();  // 获取上传的文件名
// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(scheme + endpoint, accessKeyId, accessKeySecret);

// 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
        InputStream inputStream = null;
        try {
            //获取文件的流, 文件输入流
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String fileName = module+ "/" + new DateTime().toString("yyyy/MM-dd/")
                + System.currentTimeMillis() + "_"
                + UUID.randomUUID().toString().replace("-", "").substring(0, 8)
                + originalFilename.substring(originalFilename.lastIndexOf("."));
        ossClient.putObject(bucketName, fileName, inputStream);

        String path = scheme + bucketName + "." + endpoint + "/" + fileName;
// 关闭OSSClient。
        ossClient.shutdown();

        return path;

    }

    @Override
    public void delFile(String path, String module) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(scheme + endpoint, accessKeyId, accessKeySecret);

        //文件相对路径
        path = path.substring(path.lastIndexOf(module+"/"));

// 删除文件或目录。如果要删除目录，目录必须为空。
        ossClient.deleteObject(bucketName, path);

// 关闭OSSClient。
        ossClient.shutdown();
    }
}
